package mybatis09.student;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;

import mybatis09.student.dao.StudentDao;
import mybatis09.student.entity.StudentEntity;

public class StudenTest {
	
private SqlSessionFactory sessionFactory=null;
	
	{
		Reader reader;
		try {
			//1 加载 mybatis 的配置文件（它也加载关联的映射文件）
			String resource = "mybatisConfig.xml";
			reader = Resources.getResourceAsReader(resource);
			//2 构建 sqlSession 的工厂
			sessionFactory = new SqlSessionFactoryBuilder().build(reader);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	
	/**
	 * 当查询条件一样的时候。默认开启1级缓存 也就是说 只发出1条SQL
	 */
	@Test
	public void cache01() throws Exception {
		//3 创建能执行映射文件中 sql 的 sqlSession
		SqlSession session = sessionFactory.openSession();
		StudentDao dao = session.getMapper(StudentDao.class);
		StudentEntity entity = new StudentEntity();
		List<StudentEntity> list01 = dao.findStudents(entity);
		
//		session.clearCache();
		System.out.println("sql======================================");
		List<StudentEntity> list02 = dao.findStudents(entity);
		
		for(StudentEntity student: list01){
			System.out.println(student);		
		}
		System.out.println("======================================");
		for(StudentEntity student: list02){
			System.out.println(student);		
		}
		
	}
	
	
	@Test
	public void cache02() throws Exception {
		//3 创建能执行映射文件中 sql 的 sqlSession
		SqlSession session01 = sessionFactory.openSession();
		SqlSession session02 = sessionFactory.openSession();
		
		StudentDao dao01 = session01.getMapper(StudentDao.class);
		StudentDao dao02 = session02.getMapper(StudentDao.class);
		
		StudentEntity entity = new StudentEntity();
		List<StudentEntity> list01 = dao01.findStudents(entity);
		session01.commit();
		
		System.out.println("sql======================================");
		List<StudentEntity> list02 = dao02.findStudents(entity);
		
		for(StudentEntity student: list01){
			System.out.println(student);		
		}
		System.out.println("======================================");
		for(StudentEntity student: list02){
			System.out.println(student);		
		}
		
	}
	
}
